//
//  XYSearchView.m
//  siwe
//
//  Created by 肖兰月 on 2019/3/5.
//  Copyright © 2019 siwe. All rights reserved.
//

#import "XYSearchView.h"

#define textFieldHeight 30

@interface XYSearchView ()<UITextFieldDelegate>
@property (strong, nonatomic) UITextField *searchField;
@property (assign, nonatomic) BOOL isTap;
@end

@implementation XYSearchView

- (instancetype)initWithFrame:(CGRect)frame isTap:(BOOL)isTap {
    self = [super initWithFrame:frame];
    if (self) {
        self.isTap = isTap;
        [self initSubViews];
    }
    return self;
}

- (void)initSubViews {

    _searchField = [[UITextField alloc] initWithFrame:CGRectMake(0, (self.height-textFieldHeight)/2.0, self.width, textFieldHeight)];
    _searchField.delegate = self;
    _searchField.backgroundColor = LLColorRGB(238);
    _searchField.font = LLRegularFont(15);
    //        [_searchField.layer setLayerShadow:XYColorRGB(100) offset:CGSizeMake(2, 2) radius:5];
    _searchField.layer.cornerRadius = textFieldHeight/2.0;
    _searchField.clipsToBounds = YES;
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, textFieldHeight)];
    UIImageView *search = [[UIImageView alloc] initWithFrame:CGRectMake(15, (textFieldHeight-15)/2.0, 15, 15)];
    search.image = [UIImage imageNamed:@"search_grey"];
    [leftView addSubview:search];
    _searchField.leftView = leftView;
    _searchField.leftViewMode = UITextFieldViewModeAlways;
    
    if (self.isTap) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
        [_searchField addGestureRecognizer:tap];
    } else {
        [_searchField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        _searchField.returnKeyType = UIReturnKeySearch;
    }
    [self addSubview:_searchField];
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    _searchField.placeholder = placeholder;
}

- (void)tap {
    if (self.delegate && [self.delegate respondsToSelector:@selector(didTap)]) {
        [self.delegate didTap];
    }
}

- (void)textFieldDidChange:(UITextField *)textField {
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    if ([self.delegate respondsToSelector:@selector(didSearch:)]) {
        [self.delegate didSearch:textField.text];
    }

    return NO;
}

@end
